package com.ego.member.oauth2;

import com.alibaba.fastjson.JSONObject;
import com.ego.common.constant.MemberConstant;
import com.ego.common.constant.SystemConstant;
import com.ego.common.to.member.MemberTo;
import com.ego.member.po.Member;
import com.ego.member.service.MemberService;
import com.ego.member.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * @program: ego
 * @description: 微博登录
 * @author: KamTang
 * @create: 2022-12-15 14:24
 **/
@Slf4j
public class WeiboOauth2 implements Oauth2 {

    private final ApplicationContext applicationContext = SpringUtil.getApplicationContext();

    private final MemberService memberService = applicationContext.getBean(MemberService.class);

    @Override
    public MemberTo oauth2Login(HttpServletRequest request) {
        String code = request.getParameter("code");
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>(5);
        paramMap.add("client_id", "4280652521");
        paramMap.add("client_secret", "f1db47fc253b3516a62de906fdf73235");
        paramMap.add("grant_type", "authorization_code");
        paramMap.add("redirect_uri", "http://egomall.shop:8004/oauth2.0/weibo/success");
        paramMap.add("code", code);
        ResponseEntity<JSONObject> response = restTemplate.postForEntity("https://api.weibo.com/oauth2/access_token", paramMap, JSONObject.class);

        if (response.getStatusCodeValue() == SystemConstant.Status.SUCCESS.getCode()) {
            try {
                String accessToken = Objects.requireNonNull(response.getBody()).getString("access_token");
                String uid = Objects.requireNonNull(response.getBody()).getString("uid");
                // 使用社交用户的账号信息作为注册信息
                String url = "https://api.weibo.com/2/users/show.json?access_token=" + accessToken + "&uid=" + uid;
                ResponseEntity<JSONObject> responseEntity = restTemplate.getForEntity(url, JSONObject.class);
                if (responseEntity.getStatusCodeValue() == SystemConstant.Status.SUCCESS.getCode()) {
                    JSONObject jsonObject = Objects.requireNonNull(response.getBody());
                    // 将返回结果转换为SocialAccessToken
                    MemberTo memberTo = buildMember(Objects.requireNonNull(response.getBody()), jsonObject);
                    // 如果当前用户是第一次进入网站就自动帮其注册
                    Member member = memberService.oauth2Login(memberTo);
                    if (ObjectUtils.isNotEmpty(member)) {
                        return member.toTo();
                    }
                }
            } catch (Exception e) {
                log.error("通过微博获取用户信息失败，原因：{}", e.getMessage());
            }

        }
        return null;
    }

    private MemberTo buildMember(JSONObject oauthTokenResponse, JSONObject userinfoResponse) {
        MemberTo to = new MemberTo();
        to.setSocialUid(oauthTokenResponse.getString("uid"));
        to.setAccessToken(oauthTokenResponse.getString("access_token"));
        to.setExpireTime(Long.parseLong(oauthTokenResponse.getString("expires_in")));
        to.setUsername(userinfoResponse.getString("name"));
        to.setNickname(userinfoResponse.getString("name"));
        to.setLevelId(MemberConstant.DEFAULT_MEMBER_LEVEL);
        to.setHeader(userinfoResponse.getString("profile_image_url"));
        to.setGender("m".equals(userinfoResponse.getString("gender")) ? 1 : 0);
        to.setCity(userinfoResponse.getString("location"));
        to.setCreateTime(new Date());
        return to;
    }
}
